<template>
  <view class="container">
    <!-- 搜索栏 -->
    <van-sticky>
      <view class="search-section">
        <van-search
          v-model="searchKeyword"
          placeholder="搜索消息"
          @search="handleSearch"
        />
      </view>
    </van-sticky>

    <!-- 消息分类标签 -->
    <view class="category-tabs">
      <van-tabs v-model:active="activeTab" @click-tab="onTabClick">
        <van-tab title="全部" name="all"></van-tab>
        <van-tab title="系统通知" name="system"></van-tab>
        <van-tab title="缴费提醒" name="payment"></van-tab>
        <van-tab title="医嘱提醒" name="medical"></van-tab>
        <van-tab title="预约消息" name="appointment"></van-tab>
      </van-tabs>
    </view>

    <!-- 消息列表 -->
    <view class="message-list">
      <view v-if="filteredMessages.length === 0" class="empty-state">
        <van-empty description="暂无消息" />
      </view>
      
      <van-swipe-cell
        v-for="message in filteredMessages"
        :key="message.id"
        right-width="65"
      >
        <van-cell
          :title="message.title"
          :label="message.content"
          :value="formatTime(message.createTime)"
          @click="readMessage(message)"
          :class="{ 'message-unread': !message.isRead }"
        >
          <template #icon>
            <view class="message-icon" :class="`icon-${message.type}`">
              <van-icon :name="getMessageIcon(message.type)" />
            </view>
          </template>
          <template #right-icon>
            <view v-if="!message.isRead" class="unread-dot"></view>
          </template>
        </van-cell>
        
        <template #right>
          <van-button
            square
            type="danger"
            text="删除"
            @click="deleteMessage(message.id)"
            class="delete-button"
          />
        </template>
      </van-swipe-cell>
    </view>

    <!-- 底部清空按钮 -->
    <view class="bottom-actions" v-if="filteredMessages.length > 0">
      <van-button
        type="primary"
        size="small"
        plain
        @click="markAllAsRead"
      >
        全部已读
      </van-button>
      <van-button
        type="danger"
        size="small"
        plain
        @click="clearAllMessages"
      >
        清空消息
      </van-button>
    </view>

    <!-- 消息详情弹窗 -->
    <van-popup
      v-model:show="showMessageDetail"
      position="center"
      :style="{ width: '90%', maxHeight: '70%' }"
      closeable
      @close="showMessageDetail = false"
      @click-overlay="showMessageDetail = false"
    >
      <view class="message-detail" v-if="selectedMessage">
        <view class="detail-header">
          <view class="detail-title">{{ selectedMessage.title }}</view>
          <view class="detail-time">{{ formatDateTime(selectedMessage.createTime) }}</view>
        </view>
        <view class="detail-content">
          {{ selectedMessage.content }}
        </view>
        <view class="detail-actions" v-if="selectedMessage.actionUrl">
          <van-button
            type="primary"
            size="small"
            @click="handleMessageAction"
          >
            {{ selectedMessage.actionText || '查看详情' }}
          </van-button>
        </view>
      </view>
    </van-popup>

    <!-- 底部导航 -->
    <TabBar currentTab="message" />
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";

interface Message {
  id: number;
  type: 'system' | 'payment' | 'medical' | 'appointment';
  title: string;
  content: string;
  createTime: string;
  isRead: boolean;
  actionUrl?: string;
  actionText?: string;
}

const searchKeyword = ref("");
const activeTab = ref("all");
const showMessageDetail = ref(false);
const selectedMessage = ref<Message | null>(null);

const messages = ref<Message[]>([
  {
    id: 1,
    type: "payment",
    title: "缴费成功通知",
    content: "您的预约挂号费用已缴费成功，挂号费50元，请按时就诊。",
    createTime: "2024-01-15 09:30:00",
    isRead: false,
    actionUrl: "/pages/profile/appointment-history",
    actionText: "查看挂号记录"
  },
  {
    id: 2,
    type: "appointment",
    title: "预约提醒",
    content: "您预约的张医生门诊将于明天上午9:00开始，请提前30分钟到达医院。",
    createTime: "2024-01-14 16:20:00",
    isRead: false,
    actionUrl: "/pages/profile/appointment-history"
  },
  {
    id: 3,
    type: "medical",
    title: "用药提醒",
    content: "请按时服用降压药，每日早晚各一次，注意监测血压变化。",
    createTime: "2024-01-14 08:00:00",
    isRead: true
  },
  {
    id: 4,
    type: "system",
    title: "系统维护通知",
    content: "系统将于今晚23:00-01:00进行维护，期间部分功能可能暂停使用。",
    createTime: "2024-01-13 14:15:00",
    isRead: true
  },
  {
    id: 5,
    type: "medical",
    title: "检查结果通知",
    content: "您的血常规检查结果已出，请及时查看并咨询医生。",
    createTime: "2024-01-12 11:45:00",
    isRead: false,
    actionUrl: "/pages/profile/exam-reports",
    actionText: "查看检查报告"
  }
]);

const filteredMessages = computed(() => {
  let result = messages.value;
  
  if (activeTab.value !== "all") {
    result = result.filter(msg => msg.type === activeTab.value);
  }
  
  if (searchKeyword.value) {
    result = result.filter(msg => 
      msg.title.includes(searchKeyword.value) || 
      msg.content.includes(searchKeyword.value)
    );
  }
  
  return result.sort((a, b) => new Date(b.createTime).getTime() - new Date(a.createTime).getTime());
});

const getMessageIcon = (type: string) => {
  const iconMap = {
    system: "bell-o",
    payment: "gold-coin-o", 
    medical: "records",
    appointment: "calendar-o"
  };
  return iconMap[type as keyof typeof iconMap] || "bell-o";
};

const formatTime = (timeStr: string) => {
  const now = new Date();
  const time = new Date(timeStr);
  const diff = now.getTime() - time.getTime();
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));
  
  if (days === 0) {
    return time.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    });
  } else if (days === 1) {
    return "昨天";
  } else if (days < 7) {
    return `${days}天前`;
  } else {
    return time.toLocaleDateString('zh-CN');
  }
};

const formatDateTime = (timeStr: string) => {
  const time = new Date(timeStr);
  return time.toLocaleString('zh-CN');
};

const handleSearch = () => {
  console.log("搜索消息:", searchKeyword.value);
};

const onTabClick = (tab: any) => {
  console.log("切换分类:", tab.name);
};

const readMessage = (message: Message) => {
  message.isRead = true;
  selectedMessage.value = message;
  showMessageDetail.value = true;
};

const deleteMessage = (messageId: number) => {
  uni.showModal({
    title: "删除消息",
    content: "确定要删除这条消息吗？",
    success: (res) => {
      if (res.confirm) {
        const index = messages.value.findIndex(msg => msg.id === messageId);
        if (index > -1) {
          messages.value.splice(index, 1);
          uni.showToast({
            title: "删除成功",
            icon: "success"
          });
        }
      }
    }
  });
};

const markAllAsRead = () => {
  filteredMessages.value.forEach(msg => {
    msg.isRead = true;
  });
  uni.showToast({
    title: "已全部标记为已读",
    icon: "success"
  });
};

const clearAllMessages = () => {
  uni.showModal({
    title: "清空消息",
    content: "确定要清空所有消息吗？",
    success: (res) => {
      if (res.confirm) {
        if (activeTab.value === "all") {
          messages.value = [];
        } else {
          messages.value = messages.value.filter(msg => msg.type !== activeTab.value);
        }
        uni.showToast({
          title: "清空成功",
          icon: "success"
        });
      }
    }
  });
};

const handleMessageAction = () => {
  if (selectedMessage.value?.actionUrl) {
    showMessageDetail.value = false;
    uni.navigateTo({
      url: selectedMessage.value.actionUrl
    });
  }
};

onLoad(() => {
  console.log("消息通知页面 onLoad");
});

onShow(() => {
  console.log("消息通知页面 onShow");
});
</script>

<style lang="scss">
.container {
  background-color: #f8f9fa;
  min-height: 100vh;
  padding-bottom: 100rpx;
}

.search-section {
  background: white;
  padding-bottom: 16rpx;
}

.category-tabs {
  background: white;
  border-bottom: 1rpx solid #eee;
}

.message-list {
  background: white;
}

.message-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 24rpx;
  
  &.icon-system {
    background: #f0f9ff;
    color: #1989fa;
  }
  
  &.icon-payment {
    background: #fff7e6;
    color: #ff6b35;
  }
  
  &.icon-medical {
    background: #f0f9f0;
    color: #07C160;
  }
  
  &.icon-appointment {
    background: #f5f0ff;
    color: #9c5cff;
  }
}

.message-unread {
  background: #f8f9fa;
  
  .van-cell__title {
    font-weight: bold;
  }
}

.unread-dot {
  width: 16rpx;
  height: 16rpx;
  background: #ee0a24;
  border-radius: 50%;
  margin-left: 16rpx;
}

.delete-button {
  height: 100%;
}

.bottom-actions {
  position: fixed;
  bottom: 100rpx;
  left: 0;
  right: 0;
  padding: 24rpx 32rpx;
  background: white;
  border-top: 1rpx solid #eee;
  display: flex;
  justify-content: space-around;
}

.message-detail {
  padding: 32rpx;
}

.detail-header {
  margin-bottom: 32rpx;
  
  .detail-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 16rpx;
  }
  
  .detail-time {
    font-size: 26rpx;
    color: #666;
  }
}

.detail-content {
  font-size: 28rpx;
  line-height: 1.6;
  color: #333;
  margin-bottom: 32rpx;
}

.detail-actions {
  text-align: center;
}

.empty-state {
  padding: 100rpx 0;
}
</style>
